import Vue from 'vue'
import Router from 'vue-router'
import routes from '@/router/routers'
import store from '@/store'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { setTitle } from '@/libs/utils.js'
import { getToken } from "@/libs/auth";

// 多次点击跳转同一个路由是不被允许的
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err)
}

Vue.use(Router)

const router = new Router({
    routes
})


const whiteList = ['/login', '/forget', '/401', '/404', '/500'] //免登录白名单中
const LOGIN_PAGE_NAME = 'login'

router.beforeEach((to, from, next) => {
    NProgress.configure({ showSpinner: false });
    //开启NProgress进度条
    NProgress.start()
    //设置浏览器标题
    setTitle(to.meta.title)
    const token = getToken()

    if (whiteList.indexOf(to.path) !== -1) {
        next()
    } else {
        if (!token && to.name !== LOGIN_PAGE_NAME) {
            // 未登录且要跳转的页面不是登录页
            next({
                name: LOGIN_PAGE_NAME // 跳转到登录页
            })
        } else if (!token && to.name === LOGIN_PAGE_NAME) {
            // 未登陆且要跳转的页面是登录页
            next() // 跳转
        } else if (token && to.name === LOGIN_PAGE_NAME) {
            // 已登录且要跳转的页面是登录页
            next({
                name: 'home' // 跳转到home页
            })
        } else {
            //用户刷新了页面，vuex中保存的数据丢失，需重新设置上去，并生成路由表
            if (store.getters.user == null) {
                store.dispatch('SetUserData').then(() => {
                    next() // hack方法 确保addRoutes已完成
                })
            } else {
                next()
            }
        }
    }
})

router.afterEach(to => {
    NProgress.done() //结束NProgress进度条
})

export default router